package cn.itcast.shop.category.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.shop.category.dao.CategoryDao;
import cn.itcast.shop.category.domain.Category;

@Repository("categoryDao")
@Transactional
public class CategoryDaoImpl implements CategoryDao {
	/**
	 * 注入session工厂对象
	 */
	@Autowired
	private SessionFactory sessionFactory;
	
	/**
	 * 获得session数据操作对象
	 */
	private Session getSession(){
		return sessionFactory.getCurrentSession();
	}

	/**
	 * 查询所有的一级分类
	 */
	@Override
	public List<Category> findAll() {
		String hql = "from Category";
		@SuppressWarnings("unchecked")
		List<Category> list = getSession().createQuery(hql).list();
		if(list!=null){
			return list;
		}else{
			return null;
		}
	}
	
	/**
	 * 通过指定的一级分类ID查询
	 */
	@Override
	public Category findByCid(Integer cid) {
		Category category = (Category) getSession().get(Category.class, cid);
		return category;
	}

	/**
	 * 修改一级分类
	 */
	@Override
	public void update(Category category) {
		getSession().update(category);
	}

	/**
	 * 删除一级分类
	 */
	@Override
	public void delete(Category category) {
		getSession().delete(category);
	}

	/**
	 * 新增一级分类
	 */
	@Override
	public void save(Category category) {
		getSession().save(category);
	}
}
